# -*- coding: UTF-8 -*- 
"""
author: tianke
email: ke.tian@ecarxgroup.com
datetime:  2021/11/10 4:21 下午
project: ci_conclude
filename: mongo
description：
"""

import pymongo
import traceback


class Mongo():
    def __init__(self, host="10.43.75.193", user="algo_ci", password="2I93mDZR8QSOX4R7BYbYO95p6", db='algo_ci',
                 port=27017):
        self.host = host
        self.user = user
        self.password = password
        self.db = db
        self.port = port
        self.url = f"mongodb://{self.user}:{self.password}@{self.host}/{self.db}"
        print(self.url)
        self.conn = pymongo.MongoClient(self.url, self.port)

    def find_one(self, filter, db='algo_ci', collection='hal_9000',sort_key=None):
        """
        查询一条数据
        @param filter: json 查询条件
        @param db: str 数据库
        @param collection: str collection名
        @param sort_key: list 查询条件
        @return: json 返回查询结果
        """
        try:
            db = self.conn[db]
            collection = db[collection]
            if sort_key is None:
                data = collection.find_one(filter)
            else:
                data = collection.find_one(filter,sort=sort_key)
            return data
        except:
            print(traceback.print_exc())
            return None


if __name__ == '__main__':
    mg = Mongo()
    from datetime import datetime
    now  = datetime.now()
    filter = {"timestamp": {"$gte": datetime(2021, 11, 9)},"model_version":"ecarx_last_epoch10_min_train_loss_2.2361.pth"}
    data = mg.find_one(filter)
    print(data)
